<template>
  <div class="persona-config">
    <!-- 配置头部 -->
    <div class="config-header">
      <div class="header-info">
        <h3 class="config-title">{{ isEditing ? "编辑人格" : "创建人格" }}</h3>
        <p class="config-description">配置人格的基本信息和行为参数</p>
      </div>

      <div class="header-actions">
        <Button
          v-if="isEditing"
          type="secondary"
          icon="copy"
          @click="duplicatePersona"
          title="复制人格"
        />

        <Button type="secondary" icon="x" @click="handleCancel" title="关闭" />
      </div>
    </div>

    <!-- 配置表单 -->
    <form @submit.prevent="handleSubmit" class="config-form">
      <!-- 基本信息 -->
      <div class="form-section">
        <h4 class="section-title">
          <Icon name="user" :size="16" />
          基本信息
        </h4>

        <div class="form-grid">
          <!-- 头像上传 -->
          <div class="form-group avatar-group">
            <label class="form-label">头像</label>
            <div class="avatar-upload">
              <div class="avatar-preview">
                <img
                  v-if="formData.avatar"
                  :src="formData.avatar"
                  :alt="formData.name"
                  class="avatar-image"
                />
                <Icon
                  v-else
                  name="user"
                  :size="32"
                  class="avatar-placeholder"
                />
              </div>

              <div class="avatar-actions">
                <input
                  ref="avatarInput"
                  type="file"
                  accept="image/*"
                  @change="handleAvatarChange"
                  style="display: none"
                />

                <Button
                  type="secondary"
                  size="small"
                  @click="triggerAvatarUpload"
                >
                  上传头像
                </Button>

                <Button
                  v-if="formData.avatar"
                  type="danger"
                  variant="text"
                  size="small"
                  @click="removeAvatar"
                >
                  移除
                </Button>
              </div>
            </div>
          </div>

          <!-- 名称 -->
          <div class="form-group">
            <Input
              v-model="formData.name"
              label="人格名称"
              placeholder="输入人格名称"
              required
              :error="errors.name"
              maxlength="50"
            />
          </div>

          <!-- 分类 -->
          <div class="form-group">
            <label class="form-label">分类</label>
            <select v-model="formData.category" class="form-select" required>
              <option value="">选择分类</option>
              <option value="assistant">助手</option>
              <option value="companion">陪伴</option>
              <option value="professional">专业</option>
              <option value="creative">创意</option>
              <option value="entertainment">娱乐</option>
              <option value="custom">自定义</option>
            </select>
          </div>
        </div>

        <!-- 描述 -->
        <div class="form-group">
          <Input
            v-model="formData.description"
            type="textarea"
            label="描述"
            placeholder="描述这个人格的特点和用途"
            :rows="3"
            maxlength="200"
            show-count
          />
        </div>

        <!-- 标签 -->
        <div class="form-group">
          <label class="form-label">标签</label>
          <div class="tags-input">
            <div class="tags-list">
              <span
                v-for="(tag, index) in formData.tags"
                :key="index"
                class="tag-item"
              >
                {{ tag }}
                <button
                  type="button"
                  class="tag-remove"
                  @click="removeTag(index)"
                >
                  <Icon name="x" :size="12" />
                </button>
              </span>
            </div>

            <Input
              v-model="newTag"
              placeholder="添加标签"
              size="small"
              @keydown.enter.prevent="addTag"
              @keydown.comma.prevent="addTag"
            />
          </div>
        </div>
      </div>

      <!-- 行为参数 -->
      <div class="form-section">
        <h4 class="section-title">
          <Icon name="settings" :size="16" />
          行为参数
        </h4>

        <div class="parameters-grid">
          <!-- 温度 -->
          <div class="parameter-group">
            <label class="parameter-label">
              创造性 (Temperature)
              <span class="parameter-value">{{
                formData.parameters.temperature
              }}</span>
            </label>
            <input
              v-model.number="formData.parameters.temperature"
              type="range"
              min="0"
              max="2"
              step="0.1"
              class="parameter-slider"
            />
            <div class="parameter-description">
              控制回复的创造性和随机性。值越高越有创意，值越低越稳定。
            </div>
          </div>

          <!-- Top P -->
          <div class="parameter-group">
            <label class="parameter-label">
              多样性 (Top P)
              <span class="parameter-value">{{
                formData.parameters.topP
              }}</span>
            </label>
            <input
              v-model.number="formData.parameters.topP"
              type="range"
              min="0"
              max="1"
              step="0.05"
              class="parameter-slider"
            />
            <div class="parameter-description">
              控制词汇选择的多样性。值越高选择越多样，值越低越集中。
            </div>
          </div>

          <!-- Max Tokens -->
          <div class="parameter-group">
            <label class="parameter-label">
              最大长度 (Max Tokens)
              <span class="parameter-value">{{
                formData.parameters.maxTokens
              }}</span>
            </label>
            <input
              v-model.number="formData.parameters.maxTokens"
              type="range"
              min="100"
              max="4000"
              step="100"
              class="parameter-slider"
            />
            <div class="parameter-description">限制单次回复的最大长度。</div>
          </div>

          <!-- Frequency Penalty -->
          <div class="parameter-group">
            <label class="parameter-label">
              重复惩罚 (Frequency Penalty)
              <span class="parameter-value">{{
                formData.parameters.frequencyPenalty
              }}</span>
            </label>
            <input
              v-model.number="formData.parameters.frequencyPenalty"
              type="range"
              min="0"
              max="2"
              step="0.1"
              class="parameter-slider"
            />
            <div class="parameter-description">
              减少重复内容的出现。值越高越避免重复。
            </div>
          </div>
        </div>
      </div>

      <!-- 系统提示词 -->
      <div class="form-section">
        <h4 class="section-title">
          <Icon name="message-square" :size="16" />
          系统提示词
        </h4>

        <div class="prompt-editor">
          <Input
            v-model="formData.systemPrompt"
            type="textarea"
            placeholder="输入系统提示词，定义人格的行为方式和回复风格..."
            :rows="8"
            maxlength="2000"
            show-count
          />

          <div class="prompt-templates">
            <label class="form-label">快速模板</label>
            <div class="template-buttons">
              <Button
                v-for="template in promptTemplates"
                :key="template.name"
                type="secondary"
                variant="outline"
                size="small"
                @click="applyTemplate(template)"
              >
                {{ template.name }}
              </Button>
            </div>
          </div>
        </div>
      </div>

      <!-- 高级设置 -->
      <div class="form-section">
        <h4 class="section-title">
          <Icon name="sliders" :size="16" />
          高级设置
        </h4>

        <div class="advanced-settings">
          <div class="setting-row">
            <div class="setting-info">
              <label class="setting-label">启用人格</label>
              <p class="setting-description">禁用后该人格将不可选择</p>
            </div>
            <label class="toggle-switch">
              <input
                v-model="formData.enabled"
                type="checkbox"
                class="toggle-input"
              />
              <span class="toggle-slider"></span>
            </label>
          </div>

          <div class="setting-row">
            <div class="setting-info">
              <label class="setting-label">设为默认</label>
              <p class="setting-description">新用户的默认人格选择</p>
            </div>
            <label class="toggle-switch">
              <input
                v-model="formData.isDefault"
                type="checkbox"
                class="toggle-input"
              />
              <span class="toggle-slider"></span>
            </label>
          </div>

          <div class="setting-row">
            <div class="setting-info">
              <label class="setting-label">高级人格</label>
              <p class="setting-description">需要高级权限才能使用</p>
            </div>
            <label class="toggle-switch">
              <input
                v-model="formData.isPremium"
                type="checkbox"
                class="toggle-input"
              />
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>
      </div>

      <!-- 表单操作 -->
      <div class="form-actions">
        <Button type="secondary" @click="handleCancel"> 取消 </Button>

        <Button
          v-if="isEditing"
          type="danger"
          variant="outline"
          @click="handleDelete"
        >
          删除
        </Button>

        <Button type="primary" html-type="submit" :loading="saving">
          {{ isEditing ? "保存" : "创建" }}
        </Button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { usePersonaStore } from "@/stores/persona";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";
import Input from "@/components/common/Input.vue";

interface Persona {
  id?: string;
  name: string;
  description: string;
  avatar?: string;
  category: string;
  tags: string[];
  enabled: boolean;
  isDefault?: boolean;
  isPremium?: boolean;
  systemPrompt: string;
  parameters: {
    temperature: number;
    topP: number;
    maxTokens: number;
    frequencyPenalty: number;
  };
}

interface Props {
  persona?: Persona;
  visible?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
});

const emit = defineEmits<{
  save: [persona: Persona];
  cancel: [];
  delete: [personaId: string];
}>();

// Store
const personaStore = usePersonaStore();

// 响应式数据
const saving = ref(false);
const newTag = ref("");
const avatarInput = ref<HTMLInputElement>();

// 表单数据
const formData = reactive<Persona>({
  name: "",
  description: "",
  avatar: "",
  category: "",
  tags: [],
  enabled: true,
  isDefault: false,
  isPremium: false,
  systemPrompt: "",
  parameters: {
    temperature: 0.7,
    topP: 0.9,
    maxTokens: 2000,
    frequencyPenalty: 0.0,
  },
});

// 表单验证错误
const errors = reactive({
  name: "",
});

// 计算属性
const isEditing = computed(() => !!props.persona?.id);

// 提示词模板
const promptTemplates = [
  {
    name: "友好助手",
    content:
      "你是一个友好、乐于助人的AI助手。请用温和、耐心的语气回答用户的问题，并尽可能提供有用的信息和建议。",
  },
  {
    name: "专业顾问",
    content:
      "你是一个专业的顾问，具有丰富的知识和经验。请用专业、准确的语言回答问题，并提供详细的分析和建议。",
  },
  {
    name: "创意伙伴",
    content:
      "你是一个富有创意和想象力的伙伴。请用生动、有趣的方式回答问题，并鼓励用户发挥创造力。",
  },
  {
    name: "学习导师",
    content:
      "你是一个耐心的学习导师。请用简单易懂的语言解释复杂概念，并通过例子和类比帮助用户理解。",
  },
];

// 方法
const initializeForm = () => {
  if (props.persona) {
    Object.assign(formData, {
      ...props.persona,
      tags: [...(props.persona.tags || [])],
    });
  } else {
    // 重置表单
    Object.assign(formData, {
      name: "",
      description: "",
      avatar: "",
      category: "",
      tags: [],
      enabled: true,
      isDefault: false,
      isPremium: false,
      systemPrompt: "",
      parameters: {
        temperature: 0.7,
        topP: 0.9,
        maxTokens: 2000,
        frequencyPenalty: 0.0,
      },
    });
  }

  // 清空错误
  errors.name = "";
};

const validateForm = (): boolean => {
  errors.name = "";

  if (!formData.name.trim()) {
    errors.name = "请输入人格名称";
    return false;
  }

  if (formData.name.length > 50) {
    errors.name = "人格名称不能超过50个字符";
    return false;
  }

  return true;
};

const handleSubmit = async () => {
  if (!validateForm()) return;

  saving.value = true;

  try {
    const personaData = {
      ...formData,
      tags: formData.tags.filter((tag) => tag.trim()),
    };

    if (isEditing.value) {
      await personaStore.updatePersona(personaData);
    } else {
      await personaStore.createPersona(personaData);
    }

    emit("save", personaData);
  } catch (error) {
    console.error("保存人格失败:", error);
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  emit("cancel");
};

const handleDelete = async () => {
  if (!props.persona?.id) return;

  if (confirm(`确定要删除人格 "${formData.name}" 吗？此操作不可撤销。`)) {
    try {
      await personaStore.deletePersona(props.persona.id);
      emit("delete", props.persona.id);
    } catch (error) {
      console.error("删除人格失败:", error);
    }
  }
};

const duplicatePersona = () => {
  const duplicated = {
    ...formData,
    id: undefined,
    name: `${formData.name} (副本)`,
    isDefault: false,
  };

  Object.assign(formData, duplicated);
};

// 头像处理
const triggerAvatarUpload = () => {
  avatarInput.value?.click();
};

const handleAvatarChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];

  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }
};

const removeAvatar = () => {
  formData.avatar = "";
};

// 标签处理
const addTag = () => {
  const tag = newTag.value.trim();
  if (tag && !formData.tags.includes(tag) && formData.tags.length < 10) {
    formData.tags.push(tag);
    newTag.value = "";
  }
};

const removeTag = (index: number) => {
  formData.tags.splice(index, 1);
};

// 模板应用
const applyTemplate = (template: any) => {
  formData.systemPrompt = template.content;
};

// 生命周期
onMounted(() => {
  initializeForm();
});

// 监听props变化
watch(
  () => props.persona,
  () => {
    initializeForm();
  },
  { deep: true },
);
</script>

<style scoped>
/* 人格配置基础样式 */
.persona-config {
  background-color: var(--bg-primary);
  border-radius: 12px;
  overflow: hidden;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

/* 配置头部 */
.config-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
}

.header-info {
  flex: 1;
}

.config-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px;
}

.config-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 配置表单 */
.config-form {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

/* 表单区块 */
.form-section {
  margin-bottom: 32px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border-color);
}

/* 表单网格 */
.form-grid {
  display: grid;
  grid-template-columns: auto 1fr 1fr;
  gap: 16px;
  align-items: start;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.avatar-group {
  grid-row: span 3;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 6px;
}

.form-select {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
}

.form-select:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 头像上传 */
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid var(--border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: var(--text-tertiary);
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

/* 标签输入 */
.tags-input {
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 8px;
  background-color: var(--bg-primary);
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background-color: var(--primary-color-light);
  color: var(--primary-color);
  border-radius: 4px;
  font-size: 12px;
}

.tag-remove {
  border: none;
  background: transparent;
  color: inherit;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
}

/* 参数网格 */
.parameters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.parameter-group {
  padding: 16px;
  background-color: var(--bg-secondary);
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.parameter-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.parameter-value {
  font-family: monospace;
  background-color: var(--bg-tertiary);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.parameter-slider {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: var(--bg-tertiary);
  outline: none;
  margin-bottom: 8px;
}

.parameter-slider::-webkit-slider-thumb {
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--primary-color);
  cursor: pointer;
}

.parameter-slider::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--primary-color);
  cursor: pointer;
  border: none;
}

.parameter-description {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.4;
}

/* 提示词编辑器 */
.prompt-editor {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.prompt-templates {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.template-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 高级设置 */
.advanced-settings {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.setting-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: var(--bg-secondary);
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.setting-info {
  flex: 1;
}

.setting-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.setting-description {
  font-size: 12px;
  color: var(--text-secondary);
  margin: 0;
}

/* 切换开关 */
.toggle-switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
}

.toggle-input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--bg-tertiary);
  transition: 0.2s;
  border-radius: 24px;
}

.toggle-slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.2s;
  border-radius: 50%;
}

.toggle-input:checked + .toggle-slider {
  background-color: var(--primary-color);
}

.toggle-input:checked + .toggle-slider:before {
  transform: translateX(20px);
}

/* 表单操作 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 24px;
  border-top: 1px solid var(--border-color);
  margin-top: 32px;
}

/* 响应式 */
@media (max-width: 768px) {
  .config-header {
    padding: 16px 20px;
  }

  .config-form {
    padding: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .form-group.avatar-group {
    grid-row: span 1;
  }

  .avatar-upload {
    flex-direction: row;
    align-items: center;
  }

  .parameters-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .form-actions {
    flex-direction: column-reverse;
  }
}

@media (max-width: 480px) {
  .config-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: flex-end;
  }

  .config-form {
    padding: 16px;
  }

  .template-buttons {
    flex-direction: column;
  }
}

/* 滚动条样式 */
.config-form::-webkit-scrollbar {
  width: 6px;
}

.config-form::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 3px;
}

.config-form::-webkit-scrollbar-thumb {
  background: var(--text-tertiary);
  border-radius: 3px;
}

.config-form::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}
</style>
